'use strict';

const {app, assert} = require('egg-mock/bootstrap');
const path = require('path');

function randomInt() {
  return (Math.random() * 10000).toFixed(0);
}

describe('TopicControllerTest', () => {
  let ctx, mockUser;

  before(async () => {
    ctx = app.mockContext();


    mockUser = (isAdmin = false) => {
      app.mockContext({
        user: {
          name: '殷海翔',
          _id: '5c7cd4f781c857816114c940',
          is_admin: isAdmin,
        },
      });
      app.mockCsrf();
    };
  });

  it('should GET /topic/:tid ok', async () => {
    await app.httpRequest().get(`/topic/${topicId}`).expect(200);
    await app.httpRequest().get('/topic/123').expect(404);
    mockUser();
    ctx.service.cacheSvc.setex('no_reply_topics', null, 60);
    await app.httpRequest().get(`/topic/${topicId}`).expect(200);
  });


  it('should POST /topic/create forbidden', async () => {
    app.mockCsrf();
    await app.httpRequest().post('/topic/create').expect(403);
  });

  it('should POST /topic/create forbidden', async () => {
    mockUser();
    app.mockCsrf();
    await app.httpRequest().post('/topic/create')
      .send({
        invalid_field: 'not make sense',
      })
      .expect(422);
  });

  it('should POST /topic/create per day limit works', async () => {
    mockUser();
    app.mockCsrf();
    for (let i = 0; i < 9; i++) {
      await app.httpRequest().post('/topic/create')
        .send({
          tab: 'share',
          title: `topic测试标题${i + 1}`,
          content: 'topic test topic content',
        })
        .expect(302);
    }
    await app.httpRequest().post('/topic/create')
      .send({
        tab: 'share',
        title: 'topic测试标题11',
        content: 'topic test topic content',
      })
      .expect(403);
  });

  it('should POST /topic/:tid/top ok', async () => {
    mockUser();
    const res = await app.httpRequest().post(`/topic/${topicId}/top`);
    assert(res.text.includes('需要管理员权限。'));
    mockUser(true);
    await app.httpRequest().post(`/topic/${objectId}/top`).expect(404);
    await app.httpRequest().post(`/topic/${topicId}/top`).expect(200);
  });

  it('should POST /topic/:tid/good ok', async () => {
    mockUser();
    const res = await app.httpRequest().post(`/topic/${topicId}/good`);
    assert(res.text.includes('需要管理员权限。'));
    mockUser(true);
    await app.httpRequest().post(`/topic/${objectId}/good`).expect(404);
    await app.httpRequest().post(`/topic/${topicId}/good`).expect(200);
  });

  it('should POST /topic/:tid/lock ok', async () => {
    mockUser();
    const res = await app.httpRequest().post(`/topic/${topicId}/lock`);
    assert(res.text.includes('需要管理员权限。'));
    mockUser(true);
    await app.httpRequest().post(`/topic/${objectId}/lock`).expect(404);
    await app.httpRequest().post(`/topic/${topicId}/lock`).expect(200);
  });

  it('old should POST /topic/:tid/edit ok', async () => {
    const body = {
      title: '',
      tab: '',
      content: '',
    };

    fakeUser();
    await app
      .httpRequest()
      .post(`/topic/${topicId}/edit`)
      .send(body)
      .expect(403);

    mockUser();
    await app
      .httpRequest()
      .post(`/topic/${objectId}/edit`)
      .send(body)
      .expect(404);

    const r1 = await app
      .httpRequest()
      .post(`/topic/${topicId}/edit`)
      .send(body);
    assert(r1.text.includes('标题不能是空的。'));

    body.title = 'hi';
    const r2 = await app
      .httpRequest()
      .post(`/topic/${topicId}/edit`)
      .send(body);
    assert(r2.text.includes('标题字数太多或太少。'));

    body.title = '这是一个大标题';
    const r4 = await app
      .httpRequest()
      .post(`/topic/${topicId}/edit`)
      .send(body);
    assert(r4.text.includes('必须选择一个版块。'));

    body.tab = 'share';
    const r3 = await app
      .httpRequest()
      .post(`/topic/${topicId}/edit`)
      .send(body);
    assert(r3.text.includes('内容不可为空。'));

    body.content = 'hi';
    await app
      .httpRequest()
      .post(`/topic/${topicId}/edit`)
      .send(body)
      .expect(302);
  });

  it('should POST /topic/collect ok', async () => {
    mockUser();
    const result1 = await app
      .httpRequest()
      .post('/topic/collect')
      .send({
        topic_id: objectId,
      });

    assert(JSON.parse(result1.text).status === 'failed');

    await app
      .httpRequest()
      .post('/topic/collect')
      .send({
        topic_id: topicId,
      })
      .expect(200);

    const result2 = await app
      .httpRequest()
      .post('/topic/collect')
      .send({
        topic_id: topicId,
      });

    assert(JSON.parse(result2.text).status === 'failed');
  });

  it('should POST /topic/de_collect ok', async () => {
    fakeUser();
    const result1 = await app
      .httpRequest()
      .post('/topic/de_collect')
      .send({
        topic_id: topicId,
      });
    assert(JSON.parse(result1.text).status === 'failed');

    mockUser();
    const result2 = await app
      .httpRequest()
      .post('/topic/de_collect')
      .send({
        topic_id: objectId,
      });
    assert(JSON.parse(result2.text).status === 'failed');

    await app
      .httpRequest()
      .post('/topic/de_collect')
      .send({
        topic_id: topicId,
      })
      .expect(200);
  });

  it('should POST /topic/:tid/delete ok', async () => {
    fakeUser();
    await app.httpRequest().post(`/topic/${topicId}/delete`).expect(403);
    mockUser();
    await app.httpRequest().post(`/topic/${topicId}/delete`).expect(200);
    await app.httpRequest().post(`/topic/${objectId}/delete`).expect(422);
  });

  it('should POST /upload ok', async () => {
    const file = path.resolve(__dirname, '../../../app/public/images/logo.png');
    mockUser();
    await app
      .httpRequest()
      .post('/upload')
      .attach('logo', file)
      .expect(200);
  });

  it('should POST /upload forbidden', async () => {
    const file = path.resolve(__dirname, '../../../app/public/images/logo.png');
    await app
      .httpRequest()
      .post('/upload')
      .attach('logo', file)
      .expect(403);
  });


  it('incrementVisitCount', async () => {
    app.mockCsrf();
    let topic_id = '5f748beccc08633c086adf38';
    const res = await app.httpRequest().post(`/topic/${topic_id}/incrementVisitCount`);
    console.log(res.body);
    assert(res.status = 200);
  });


  // 增加original_tag后的单测----------------------------
  // 进入创建文章页面
  it('should GET /topic/create ok', async () => {
    mockUser();
    await app.httpRequest().get('/topic/create').expect(200);
  });

  // 发表新文章接口
  it('should POST /topic/create ok', async () => {
    mockUser();
    app.mockCsrf();
    await app.httpRequest().post('/topic/create')
      .send({
        tab: 'share',
        title: 'topic测试标题2',
        content: 'topic test topic content',
        original_tags: '你2 你3 你4 你5'
      })
      .expect(302);
  });

  // 进入文章编辑页面
  it('should GET /topic/:tid/edit ok', async () => {
    mockUser();
    const topic_id = '5fd45f0054bf5605513fe6df';
    await app.httpRequest().get(`/topic/${topic_id}/edit`).expect(200);
  });

  // 编辑文章接口
  it('should POST /topic/:tid/edit ok', async () => {
    mockUser();
    app.mockCsrf();
    const topic_id = '5fd45f0054bf5605513fe6df';

    await app.httpRequest().post(`/topic/${topic_id}/edit`)
      .send({
        tab: 'original',
        title: 'topic测试标题2',
        content: 'topic test topic content',
        original_tags: '你好2 测试标签1',
        is_private: 1
      })
      .expect(302);
  });

  // 进入文章详情页
  it('should GET /topic/:tid ok', async () => {
    mockUser();
    const topic_id = '5fd45f0054bf5605513fe6df';
    await app.httpRequest().get(`/topic/${topic_id}`).expect(200);
  });


  // 进入"我的文章"页面
  it('should GET /user/:name/my_topics ok', async () => {
    mockUser();
    const user_name = '殷海翔';
    await app.httpRequest().get(`/user/${encodeURI(user_name)}/my_topics`).expect(200);
  });


  // 展示用户所有原创标签及标签包含文章的数量, 可以按照标签名模糊搜索
  it('should GET /topics/listOriginalTags ok', async () => {
    const data = {
      access_token: 'edd8bcd1-db39-4ea8-8221-3849349eccc2',
      tag_name: '你好'
    }
    let result = await app.httpRequest()
      .post(`/api/v1/topic/listOriginalTags`)
      .send(data);

    console.log(result.body);
    assert(result.body.status == 'success');
  });

  // 判断已有标题是否存在
  it('assertTopicExist', async () => {
    mockUser();
    const data = {
      title: '测试原创标签2',
    }
    let result = await app.httpRequest()
      .post(`/topic/assertTopicExist`)
      .send(data);

    console.log(result.body);
    assert(result.body.success == true);
  });


});
